package unsplash;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class Download {
    private String savePath;
    private String resultUrl;
    private String fileName;

    public Download(String savePath, String resultUrl, String fileName) {
        this.savePath = savePath;
        this.resultUrl = resultUrl;
        this.fileName = fileName;
    }

    public void getInternetRes() throws IOException {
        URL url;
        HttpURLConnection connection;
        InputStream in = null;
        FileOutputStream out = null;
        try {
            url = new URL(resultUrl);
            connection = (HttpURLConnection) url.openConnection();
            in = connection.getInputStream();
            byte[] data = getByteData(in);

            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            File res = new File(file + File.separator + fileName);
            out = new FileOutputStream(res);
            out.write(data);
        } finally {
            if (null != out) out.close();
            if (null != in) in.close();
        }
    }

    private byte[] getByteData(InputStream in) throws IOException {
        byte[] b = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len;
        while ((len = in.read(b)) != -1) {
            bos.write(b, 0, len);
        }
        if (null != bos) {
            bos.close();
        }
        return bos.toByteArray();
    }
}
